package com.cloudwave.trailends.web.interceptors;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.cloudwave.base.action.AppAction;
import com.cloudwave.base.utils.SpringUtil;
import com.cloudwave.trailends.service.UserService;

/**
 * @description Token拦截器
 * @author 龙雪
 * 2013年12月6日 上午11:51:04
 * http://my.oschina.net/uniquejava/blog/83657
 */

public class TokenInteceptor extends HandlerInterceptorAdapter {
	private final static Logger logger = LoggerFactory.getLogger(TokenInteceptor.class);
	
	private List<String> excludedUrls;

	public void setExcludedUrls(List<String> excludedUrls) {
		this.excludedUrls = excludedUrls;
	}
	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		logger.debug("TokenInteceptor --> preHandle");
		logger.debug("handler:"+handler);
		
		String requestUri = request.getRequestURI();
		if (CollectionUtils.isNotEmpty(excludedUrls)) {
			for (String url : excludedUrls) {
				if ( requestUri.startsWith(url) ) {
					return super.preHandle(request, response, handler);
				}
			}
		}
		
//		Object obj = request.getAttribute("token");
//		if ( obj == null ) {
//			response.sendError(403);
//			return false;
//		}
		
		String token = request.getParameter("token");
		if ( StringUtils.isNotEmpty(token) ) {
//			UserService userService = (UserService) SpringUtil.getObject("userService");
			UserService userService = (UserService) SpringUtil.getObject(UserService.class);
			Long userId = userService.findIdByToken(token);
			
			if (userId == null || userId == 0) {
				response.sendError(403);
				return false;
			}
			HandlerMethod hm = (HandlerMethod) handler;
			AppAction bc = (AppAction) hm.getBean();
			bc.setUserId(userId);
			bc.setToken(token);
			
			return super.preHandle(request, response, handler);
		}
		response.sendError(403);
		return false;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		logger.debug("TokenInteceptor --> postHandle");
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		logger.debug("TokenInteceptor --> afterCompletion");
	}

}
